package com.mrent.web.controller.manager;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.google.appengine.api.datastore.Blob;
import com.mrent.entity.Goods;
import com.mrent.entity.OrderManager;
import com.mrent.entity.Picture;
import com.mrent.service.GoodsService;
import com.mrent.service.Page;
import com.mrent.service.PictureService;
import com.mrent.util.Constance;
import com.mrent.util.RenderUtil;
import com.mrent.util.Utils;
import com.mrent.web.form.GoodsForm;

@Controller
public class ManagerGoodsController {
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private PictureService pictureService;
	
	/**
	 * 商品管理.
	 * @return
	 */
	@RequestMapping("/manager/goods/index")
	public String index(){
		return "manager/goods/home";
	}
	
	/**
	 * 商品列表.
	 * 
	 * @param session
	 * @param response
	 * @param page
	 * @return
	 */
	@RequestMapping("/manager/goods/list")
	public String list(HttpSession session,HttpServletResponse response,String page){
		int p = 1;
		Page pp = new Page();
		try{
			p = Integer.parseInt(page);
		}catch(Exception e){
			p = 1;
		}
		pp.setPageNo(p);
		pp.setPageSize(Constance.DEFAULT_PAGE_SIZE);
		OrderManager om = (OrderManager)session.getAttribute(Constance.SESSION_MANAGER_NAME);
		List<Goods> goods ;
		if(om != null){
			goods = goodsService.listGoods(pp, om.getOrderMember());
			Map<String,Object> json = new HashMap<String,Object>();
			json.put("rows", goods);
			json.put("total", pp.getTotalCount());
			RenderUtil.renderJson(json,response);
		}
		
		return null;
	}
	
	/**
	 * 商品添加跳转.
	 * 
	 * @return
	 */
	@RequestMapping("/manager/goods/add")
	public String add(){
		return "manager/goods/add";
	}

	/**
	 * 保存商品.
	 * 
	 * @return
	 */
	@RequestMapping("/manager/goods/save")
	public String save(Goods goods,GoodsForm form,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> json = new HashMap<String,Object>();
		//处理缩略图.
		MultipartFile[] files = form.getFiles();
		for(MultipartFile file :files){
			System.out.println("save goods img....");
			InputStream stream = file.getInputStream();
			Blob productImg = new Blob(IOUtils.toByteArray(stream));
			Picture picture = new Picture();
			picture.setPictureData(productImg);
			pictureService.savePicture(picture);
			goods.setGoodsImg(picture.getPictureId());
		}
		Date now = new Date();
		Long nowtime = System.currentTimeMillis();
		goods.setGoodsNo(Utils.generDataNo());
		goods.setClickCount(Constance.CLICK_COUNT);
		goods.setAddTime(now);
		goods.setLastUpdate(now);
		goods.setIsDelete(Constance.IS_NOT_DEL);//未删除.
		OrderManager manager = (OrderManager)session.getAttribute(Constance.SESSION_MANAGER_NAME);
		goods.setManager(manager.getOrderMember());
		//促销信息设置.
		if(goods.getIsPromote() == 1){
			String promoteStart = request.getParameter("promoteStart");
			String promoteEnd = request.getParameter("promoteEnd");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(promoteStart != null && promoteStart.length() > 0){
				try{
					goods.setPromoteStartDate(sdf.parse(promoteStart));
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				goods.setPromoteStartDate(now);
			}
			if(promoteEnd != null && promoteEnd.length() > 0){
				try{
					goods.setPromoteEndDate(sdf.parse(promoteEnd));
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				Calendar c = Calendar.getInstance();
				c.add(Calendar.DATE, 1);
				goods.setPromoteEndDate(c.getTime());
			}
		}
		//拍卖信息设置.
		if(goods.getIsAuction() == 1){
			String auctionStart = request.getParameter("auctionDateStart");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(auctionStart != null && auctionStart.length() > 0){
				goods.setAuctionDate(sdf.parse(auctionStart));
			}else{
				json.put("result", "Faile");
				json.put("ErrorMsg", "请设置拍卖日期!");
				String jsonString = JSONObject.fromObject(json).toString();
				RenderUtil.renderHtml(jsonString, response);
			}
		}
		goodsService.saveGoods(goods);
		json.put("result", "Success");
		String jsonString = JSONObject.fromObject(json).toString();
		RenderUtil.renderHtml(jsonString, response);
		return null;
	}
	
	/**
	 * 跳转商品修改.
	 * 
	 * @param goodsId
	 * @param model
	 * @return
	 */
	@RequestMapping("/manager/goods/modify/{goodsId}")
	public String modify(@PathVariable Long goodsId,ModelMap model){
		Goods goods = goodsService.getGoods(goodsId);
		if(goods!=null){
			model.addAttribute("goods", goods);
		}
		return "manager/goods/modify";
	}
	
	/**
	 * 商品修改保存.
	 * 
	 * @return
	 */
	@RequestMapping("/manager/goods/update")
	public String update(Goods goods,GoodsForm form,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Goods dbGoods = goodsService.getGoods(goods.getGoodsId());
		Date now = new Date();
		Long nowtime = System.currentTimeMillis();
		goods.setClickCount(dbGoods.getClickCount());
		goods.setAddTime(dbGoods.getAddTime());
		goods.setLastUpdate(now);
		goods.setIsDelete(Constance.IS_NOT_DEL);
		goods.setManager(dbGoods.getManager());
		
		Map<String,Object> json = new HashMap<String,Object>();
		//处理缩略图.
		MultipartFile[] files = form.getFiles();
		for(MultipartFile file :files){
			System.out.println("save goods img....");
			if(file.getSize()>0){
				InputStream stream = file.getInputStream();
				Blob productImg = new Blob(IOUtils.toByteArray(stream));
				Picture picture = new Picture();
				picture.setPictureData(productImg);
				pictureService.savePicture(picture);
				goods.setGoodsImg(picture.getPictureId());
			}else{
				goods.setGoodsImg(dbGoods.getGoodsImg());
			}
		}
		
		//促销信息设置.
		if(goods.getIsPromote() == 1){
			String promoteStart = request.getParameter("promoteStart");
			String promoteEnd = request.getParameter("promoteEnd");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(promoteStart != null && promoteStart.length() > 0){
				try{
					goods.setPromoteStartDate(sdf.parse(promoteStart));
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				goods.setPromoteStartDate(now);
			}
			if(promoteEnd != null && promoteEnd.length() > 0){
				try{
					goods.setPromoteEndDate(sdf.parse(promoteEnd));
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				Calendar c = Calendar.getInstance();
				c.add(Calendar.DATE, 1);
				goods.setPromoteEndDate(c.getTime());
			}
		}
		//拍卖信息设置.
		if(goods.getIsAuction() == 1){
			String auctionStart = request.getParameter("auctionDateStart");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(auctionStart != null && auctionStart.length() > 0){
				goods.setAuctionDate(sdf.parse(auctionStart));
			}else{
				json.put("result", "Faile");
				json.put("ErrorMsg", "请设置拍卖日期!");
				String jsonString = JSONObject.fromObject(json).toString();
				RenderUtil.renderHtml(jsonString, response);
			}
		}
		goodsService.updateGoods(goods);
		json.put("result", "Success");
		String jsonString = JSONObject.fromObject(json).toString();
		RenderUtil.renderHtml(jsonString, response);
		return null;
	}
	
	/**
	 * 删除商品.
	 * 
	 * @param response
	 * @param goodsId
	 * @return
	 */
	@RequestMapping("/manager/goods/del/{goodsId}")
	public String delGoods(HttpServletResponse response,@PathVariable Long goodsId){
		Map<String,Object> json = new HashMap<String,Object>();
		goodsService.delGoods(goodsId);
		json.put("result", "Success");
		
		RenderUtil.renderJson(json, response);
		return null;
	}
	
	/**
	 * 设置镇店之宝.
	 * 
	 * @param request
	 * @param response
	 * @param goodsId
	 * @param isShopBaby
	 * @return
	 */
	@RequestMapping("/manager/goods/setShopBaby/{goodsId}")
	public String setShopBaby(HttpSession session,HttpServletRequest request,HttpServletResponse response,@PathVariable Long goodsId,Integer isShopBaby){
		OrderManager manager = (OrderManager)session.getAttribute(Constance.SESSION_MANAGER_NAME);
		boolean isHaveShopBaby = goodsService.haveShopBaby(manager.getOrderMember(), goodsId);
		if(isHaveShopBaby && isShopBaby.intValue()==1 ){
			Map<String,Object> json = new HashMap<String,Object>();
			json.put("result", "Faile");
			json.put("ErrorCode", "-1");
			RenderUtil.renderJson(json, response);
			return null;
		}
		Goods goods = goodsService.getGoods(goodsId);
		goods.setIsShopBaby(isShopBaby);
		goodsService.updateGoods(goods);
		
		Map<String,Object> json = new HashMap<String,Object>();
		json.put("result", "Success");
		RenderUtil.renderJson(json, response);
		return null;
	}

}
